package org.huangrui.design.pattern.singleton;

import java.util.concurrent.*;


/**
 * 双重检查
 * dcl + volatile
 * @author hr
 * @create 2025-09-09 15:19
 */
public class Singleton5 {
	private static volatile Singleton5 instance;
	private Singleton5(){
	}
	public static Singleton5 getInstance(){
		if(instance == null){
			synchronized (Singleton5.class) { // Double check Lock
				if(instance == null){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					instance = new Singleton5();
				}
			}
		}
		return instance;
	}

	public static void main(String[] args) throws ExecutionException, InterruptedException {
		/*Singleton5 s1 = Singleton5.getInstance();
		Singleton5 s2 = Singleton5.getInstance();
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);*/
		Callable<Singleton5> c = new Callable<Singleton5>() {
			@Override
			public Singleton5 call() throws Exception {
				return Singleton5.getInstance();
			}
		};
		ExecutorService es = Executors.newFixedThreadPool(2);
		Future<Singleton5> f1 = es.submit(c);
		Future<Singleton5> f2 = es.submit(c);
		Singleton5 s1 = f1.get();
		Singleton5 s2 = f2.get();
		System.out.println(s1);
		System.out.println(s2);
		System.out.println(s1 == s2);
		es.shutdown();

		for (int i = 1; i <= 10; i++) {
		    new Thread(() ->{
				System.out.println("hashCode "+Singleton5.getInstance().hashCode());
		    },String.valueOf(i)).start();
		}
	}
}
